<template>
	<view class="page group-progress">
		<!-- 商品 -->
		<view class="goods flex-row-start box-shadow" @click="goNext('/pages/group/detail?id='+goodsobj.goods_id)">
			<view class="left bg-cover" :style="{backgroundImage: 'url(' + goodsobj.logo + ')'}"></view>
			<view class="right flex-1 flex-column-between">
				<view class="font14">{{goodsobj.name?goodsobj.name:''}}</view>
				<view class="flex-row-between">
					<view class="font18 font-assist">
						<text class="font11">￥</text>{{goodsobj.group_price?goodsobj.group_price:''}}
						<text class="font12 font-999999 font-line">￥{{goodsobj.price?goodsobj.price:''}}</text>
					</view>
					<view class="font12 font-999999">已售{{goodsobj.sales_actual?goodsobj.sales_actual+goodsobj.sales_initial:0}}</view>
				</view>
			</view>
		</view>
		<!-- 进度 -->
		<view class="progress box-shadow">
			<view class="flex-row-center" v-if="datainfo.name_is=='normal'">
				<image class="icon" src="https://static.newbeaconhotels.com/app/hotel/group/icon-wait1.png"></image>
				<view class="font14">等待成团，仅剩<text class="font-assist">{{datainfo.number}}</text>个名额</view>
			</view>
			<view class="flex-row-center" v-else>
				<image v-if="datainfo.status=='end'" class="icon"
					src="https://static.newbeaconhotels.com/app/hotel/group/icon-wait2.png"></image>
				<image v-else class="icon" src="https://static.newbeaconhotels.com/app/hotel/group/icon-wait3.png"></image>
				<view class="font14">{{datainfo.name_is}}</view>
			</view>
			<view class="count flex-row-center" v-if="datainfo.timeobj.show">
				<text class="font12">距结束：</text>
				<uni-countdown class="group-countdown" backgroundColor="#817fa5" color="#ffffff" splitorColor="#1e1e1e"
					:day="datainfo.timeobj.day" :hour="datainfo.timeobj.hour" :minute="datainfo.timeobj.minute"
					:second="datainfo.timeobj.second" :show-colon="false" />
				<!-- <view v-else class="font12">已结束</view> -->
			</view>
			<view class="flex-row-center">
				<block v-for="(item, index) in member" :key="index">
					<view class="member yes bg-cover" :style="{backgroundImage: 'url(' + item.user_avatar + ')'}">
						<view v-if="item.is_chief==1" class="head font11 font-ffffff flex-column-center">团长</view>
					</view>
				</block>
				<view class="member flex-column-center" v-for="n in datainfo.number" :key="n">?</view>
			</view>
			<!--  #ifdef  MP-WEIXIN -->
			<button v-if="datainfo.status=='normal'&&datainfo.spell_user_status"
				class="btn font15 font-ffffff flex-column-center" open-type="share" title="邀请参团">邀请参团</button>
			<!--  #endif -->
			<!--  #ifdef  H5 -->
			<view v-if="datainfo.status=='normal'&&datainfo.spell_user_status"
				class="btn font15 font-ffffff flex-column-center" @click="Ongive">
				邀请参团</view>
			<!--  #endif -->
			<view v-if="datainfo.status=='normal'&&!datainfo.spell_user_status"
				class="btn font15 font-ffffff flex-column-center" @click="openSpec">立即参团</view>
			<view v-if="datainfo.status=='end'&&datainfo.spell_user_status"
				class="btn font15 font-ffffff flex-column-center"
				@click="goNext('/pages/group/orderDetail?code='+datainfo.order_code)">查看订单</view>
			<view v-if="datainfo.status=='end'&&!datainfo.spell_user_status"
				class="btn font15 font-ffffff flex-column-center"
				@click="goNext('/pages/group/detail?id='+goodsobj.goods_id)">重新开团</view>
			<view v-if="datainfo.status=='hidden'||datainfo.status=='deleted'"
				class="btn font15 font-ffffff flex-column-center"
				@click="goNext('/pages/group/detail?id='+goodsobj.goods_id)">重新开团</view>
		</view>
		<!-- 攻略 -->
		<view class="rule box-shadow">
			<view class="title flex-row-center font14">拼团攻略</view>
			<view class="content">
				<rich-text :nodes="detail"></rich-text>
			</view>
		</view>
		<!-- 规格弹窗 -->
		<uni-popup ref="specification" type="bottom">
			<view class="specification">
				<uni-icons class="close" type="close" size="22" color="#666666" @tap="closeSpec"></uni-icons>
				<view class="part1 flex-row-start">
					<image class="image bg-cover"
						:src="findItem.spec_image?imgFullUrl+findItem.spec_image:goodsobj.logo" mode="">
					</image>
					<view class="price">
						<view class="font-assist font11">￥<text class="font18">
								{{findItem.goods_price?findItem.group_price:goodsobj.group_price}}</text>
						</view>
						<view class="font12 font-646464">库存 {{findItem.stock_num?findItem.stock_num:specobj.stock_num}}
							件</view>
					</view>
				</view>
				<view class="part2 font13" v-if="datainfo.goods_info.spec_type == 10">默认规格</view>
				<view class="part2" v-else v-for="(item,index) in specobj.spec" :key="index">
					<view class="font13">{{item.spec_name}}</view>
					<view @click="Onchoice(item1,index,index1)"
						:class="!item1.show?'font-969696':goodsIndex[index] == index1?'font-ff3c37 back-ffe9e8':'font-323232'"
						class="tag" v-for="(item1,index1) in item.value" :key="index1">{{item1.spec_value}}</view>
				</view>
				<view class="part3 flex-row-between">
					<view class="font13">数量</view>
					<uni-number-box v-model="buyNum" :min="1" :max="maxBuyNum" @change="buyNumChange"></uni-number-box>
				</view>
				<!-- <view class="btn">单独预订</view> -->
				<view class="btn" @click="Oncart">参加拼团</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				id: null, //拼团ID
				datainfo: {}, //总数据
				goodsobj: {}, //商品数据
				imgFullUrl: this.$Config.http_static, //图片地址
				needNumber: 3, // 共需要的人数
				lackNumber: 0, // 未参加的人数
				// 用户信息
				userInfo: {},
				idInfo: {},
				member: [],
				detail: '',
				specobj: {}, //规格对象
				shopItemInfo: {}, //存放要和选中的值进行匹配的数据
				goodsArr: [], //存放被选中的值
				goodsIndex: [], //是否选中 因为不确定是多规格还是单规格，所以这里定义数组来判断
				goodsName: [], //选择文字
				findItem: {}, //数据
				showAttr: "",
				// 数量
				maxBuyNum: 1,
				buyNum: 1,
				buyNumtype: false, //一进来不执行
			}
		},
		onLoad: function(options) {
			// 从缓存中拿取各种id信息
			this.idInfo = uni.getStorageSync('idInfo')
			let query = {}
			if (this.$Route.query.scene) {
				query = this.$base.OnWxoptions(this.$Route.query.scene)
			} else {
				query = options
			}
			this.id = query.id
			if (uni.getStorageSync('token')) {
				/*获取用户信息*/
				this.$Http({
					url: 'user',
					token: true
				}).then(res => {
					if (res.code == 1) {
						this.userInfo = res.data
						this.OnDetails()
					}
				});
			} else {
				this.OnDetails()
			}
			//公共配置
			this.OngroupBuy()

		},
		onShow() {
			// this.lackNumber = this.needNumber - this.member.length
		},
		methods: {
			//公共配置
			OngroupBuy() {
				this.$Http({
					url: 'groupBuy',
					token: true,
					data: {},
				}).then(res => {
					if (res.code == 1) {
						res.data.spell_strategy = res.data.spell_strategy ? res.data.spell_strategy.replace(
							/\<img/g, '<img style="display: block;max-width: 100%;height: auto;"') : ''
						this.detail = res.data.spell_strategy
					}
				});
			},
			//拼团详情
			OnDetails() {
				this.$Http({
					url: 'detailsSpell',
					token: true,
					type: 'POST',
					data: {
						order_spell_id: this.id
					},
				}).then(res => {
					if (res.code == 1) {
						var nowTime = Math.round(new Date().getTime());
						var ms = (res.data.end_time * 1000) - nowTime;
						var timeobj = {}
						if (res.data.status == 'normal') {
							if (ms > 0) {
								var day = Math.floor(ms / (1000 * 60 * 60 * 24));
								var hour = Math.floor(ms / (1000 * 60 * 60)) % 24;
								if (day > 0) {
									hour = (day * 24) + hour
								}
								var minute = Math.floor(ms / (1000 * 60)) % 60;
								var second = Math.floor(ms / 1000) % 60;
								timeobj = {
									'day': day,
									'hour': hour,
									'minute': minute,
									'second': second,
									'show': true
								}
							} else {
								timeobj = {}
							}
						}
						res.data.number = this.$base.numSub(res.data.spell_number, res.data.count_user)
						res.data.timeobj = timeobj
						res.data.goods_info.logo = this.imgFullUrl + res.data.goods_info.logo
						//判断
						if (res.data.status == 'normal') {
							res.data.name_is = 'normal'

							let message_id = '';
							let $C = this.idInfo.Cid
							if ($C) {
								message_id = 'Pid.' + this.idInfo.Pid + ',Fid.' + this.idInfo.Fid + ',id.' + this
									.id + ',Cid.' + $C
							} else {
								message_id = 'Pid.' + this.idInfo.Pid + ',Fid.' + this.idInfo.Fid + ',id.' + this
									.id
							}

							//修改分享
							if (res.data.spell_user_status) {
								// #ifdef MP-WEIXIN
								this.share.type = true
								this.share.title = '您的好友邀请您拼团~'
								this.share.desc = res.data.goods_info.name
								this.share.imageUrl = res.data.goods_info.logo
								this.share.path = '/pages/group/progress?scene=' + message_id
								// #endif
							} else {
								//获取规格
								this.OngoodsSpec(res.data.goods_info.goods_id)
							}
						}
						if (res.data.status == 'hidden') {
							res.data.name_is = '拼团异常'
						}
						if (res.data.status == 'end') {
							res.data.name_is = '恭喜您,拼团成功!'
						}
						if (res.data.status == 'deleted') {
							res.data.name_is = '很遗憾,拼团失败!'
						}
						// 	if (res.data.spell_user_status) {

						// 	} else {
						// 		res.data.name_is = '很遗憾,拼团失败!'
						// 	}
						this.member = res.data.order_spell_user
						this.goodsobj = res.data.goods_info
						this.datainfo = res.data
					}
				});
			},
			// 打开规则弹窗
			openSpec() {
				this.$refs.specification.open()
			},
			//获取商品规格的价格
			OngoodsSpec(id) {
				this.$Http({
					url: 'goodsSpec',
					token: true,
					type: 'POST',
					data: {
						goods_id: id
					},
				}).then(res => {
					if (res.code == 1) {
						//如果是单规格
						if (this.goodsobj.spec_type == 10) {
							this.findItem = res.data.spec_rel[0]
						}
						//把所有规格当key放到一个数组里面去
						res.data.spec_rel.forEach(item => {
							this.shopItemInfo[item.spec_sku_id] = item
						})
						//所以参数加show当未选择
						res.data.spec.forEach(item => {
							item.value.forEach(item1 => {
								item1.show = true
							})
						})
						this.buyNumtype = true
						this.specobj = res.data
					}
				});
			},
			//选择
			Onchoice(item, index1, index2) {
				if (!item.show) {
					return
				}
				if (this.goodsArr[index1] != item.id) {
					this.goodsArr[index1] = item.id
					this.goodsIndex[index1] = index2
					this.goodsName[index1] = item.spec_value
				} else {
					this.goodsArr[index1] = undefined;
					this.goodsIndex[index1] = -1; //去掉选中的颜色
					this.goodsName[index1] = ''
					this.buyNum = 1
				}
				var showarr = this.goodsArr;
				var tempTop = [];
				showarr.forEach((item, i, arr) => {
					if (item) {
						tempTop.push(item)
					}
				})
				this.showAttr = tempTop.join(",");
				this.checkItem()
				tempTop = []
				this.$forceUpdate();
			},
			checkItem() {
				var option = this.specobj.spec;
				var result = []; //定义数组存储被选中的值
				option.forEach((item, index) => {
					result[index] = this.goodsArr[index] ? this.goodsArr[index] : '';
				})
				if (this.shopItemInfo[result.join(",")]) {
					this.findItem = this.shopItemInfo[result.join(",")]
					this.maxBuyNum = this.findItem.stock_num
				} else {
					this.findItem = {}
					this.maxBuyNum = 1
				}
				for (var i in option) {
					var last = result[i]; //把选中的值存放到字符串last去
					for (var k in option[i].value) {
						result[i] = option[i].value[k].id; //赋值，存在直接覆盖，不存在往里面添加name值
						option[i].value[k].show = this.isMay(result); //在数据里面添加字段isShow来判断是否可以选择
					}
					result[i] = last; //还原，目的是记录点下去那个值，避免下一次执行循环时避免被覆盖
				}
				this.specobj.spec = option
				this.$forceUpdate();
			},
			isMay: function(result) {
				for (var i in result) {
					if (result[i] == '') {
						return true; //如果数组里有为空的值，那直接返回true
					}
				}
				if (this.shopItemInfo[result.join(",")]) { //匹配选中的数据的库存，若不为空返回true反之返回false
					return this.shopItemInfo[result.join(",")].stock_num == 0 ? false : true;
				}
			},
			// 购买数量change
			buyNumChange(e) {
				if (!this.findItem.goods_id && this.buyNumtype) {
					uni.showToast({
						icon: 'none',
						duration: 2000,
						title: '请先选择规格'
					});
					return
				}
				this.buyNum = parseInt(e)
				if (this.buyNum > this.maxBuyNum && this.buyNumtype) {
					uni.showToast({
						title: '超出最大购买数量',
						icon: 'none'
					});
					return
				}
			},
			//提交订单
			Oncart() {
				if (!this.findItem.goods_id) {
					uni.showToast({
						icon: 'none',
						duration: 2000,
						title: '请先选择规格'
					});
					return
				}
				let data = {
					pay_type: 1,
					source: '',
					goods_id: this.findItem.goods_id,
					goods_spec_id: this.findItem.goods_spec_id,
					goods_number: this.buyNum,
					order_spell_id: this.id
				}
				// #ifdef MP-WEIXIN
				data.source = 2
				// #endif
				// #ifdef H5
				data.source = 1
				// #endif
				this.$Http({
					url: 'createOrder',
					token: true,
					type: 'POST',
					data: data,
				}).then(res => {
					if (res.code == 1) {
						// this.findItem = {}
						this.$Router.push('/pages/group/book?code=' + res.data.order_code)
						this.$refs.specification.close()
					} else {
						uni.showToast({
							icon: 'none',
							duration: 2000,
							title: res.msg
						});
					}
				});
			},
			// 关闭规则弹窗
			closeSpec() {
				this.$refs.specification.close()
			},
			//跳转
			goNext(url) {
				this.$Router.push(url)
			}
		}
	}
</script>

<style lang="less">
	@import url("style.less");
</style>
